package cn.bossfriday.im.user.actors;

import cn.bossfriday.common.plugin.PluginSpringContext;
import cn.bossfriday.common.register.ActorRoute;
import cn.bossfriday.common.rpc.actor.ActorRef;
import cn.bossfriday.im.common.codec.ImTokenCodec;
import cn.bossfriday.im.common.db.entity.AppInfo;
import cn.bossfriday.im.common.entity.ImToken;
import cn.bossfriday.im.common.entity.result.Result;
import cn.bossfriday.im.common.helper.AppHelper;
import cn.bossfriday.im.common.message.rpc.user.GetTokenInput;
import cn.bossfriday.im.common.message.rpc.user.GetTokenOutput;
import cn.bossfriday.im.common.rpc.BaseActor;
import cn.bossfriday.im.common.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;

import static cn.bossfriday.im.common.constant.ImConstant.ACTOR_USER_GET_TOKEN;
import static cn.bossfriday.im.common.entity.result.ResultCode.SYSTEM_ERROR;

/**
 * GetTokenActor
 *
 * @author chenx
 */
@Slf4j
@ActorRoute(methods = ACTOR_USER_GET_TOKEN)
public class GetTokenActor extends BaseActor<GetTokenInput> {

    @Override
    public void onMessageReceived(GetTokenInput msg) {
        try {
            long appId = this.getContext().getAppId();
            String uid = msg.getUserId();
            String deviceId = msg.getDeviceId();
            long time = System.currentTimeMillis();

            // create token
            AppInfo appInfo = AppHelper.getAppInfo(appId);
            ImToken imToken = new ImToken(appId, appInfo.getAppSecret(), uid, deviceId, time);
            String token = ImTokenCodec.encode(imToken);

            // register user
            UserInfoService userInfoService = PluginSpringContext.getBean(UserInfoService.class);
            userInfoService.register(appId, uid, msg.getUserName());

            GetTokenOutput output = GetTokenOutput.builder()
                    .token(token)
                    .userId(msg.getUserId())
                    .build();
            this.getSender().tell(Result.ok(output), ActorRef.noSender());
        } catch (Exception ex) {
            log.error("GetTokenActor.onMessageReceived() error!", ex);
            this.getSender().tell(Result.error(SYSTEM_ERROR), ActorRef.noSender());
        }
    }
}